package vn.edu.uit.chemistry;

import java.io.File;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.ArrayList;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import vn.edu.uit.chemistry.model.CauHoi15;
import vn.edu.uit.chemistry.utilities.TCPClient;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.text.Html;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

public class LamBaiKT15 extends Activity {

	String title = "";
	String nameFile = "";
	String sizeFile = "";
	String sender = "";
	String path = Environment.getExternalStorageDirectory().getAbsolutePath()
			.toString()
			+ "/hoa hoc/kiem tra/kt15/";
	ArrayList<CauHoi15> listCauHoi15 = new ArrayList<CauHoi15>();
	CauHoi15 cauhoi = new CauHoi15();

	String[] cauhoi1 = { "Câu 1:", "Câu 2:", "Câu 3:", "Câu 4:", "Câu 5:",
			"Câu 6:", "Câu 7:", "Câu 8:", "Câu 9:", "Câu 10:", "Câu 11:",
			"Câu 12:", "Câu 13:", "Câu 14:", "Câu 15:" };
	String[] dapan = { "F", "F", "F", "F", "F", "F", "F", "F", "F", "F", "F", "F", "F", "F", "F" };

	ImageView imgClock;

	TextView tvTimer;
	TextView tvSoThuTuCauHoi;
	TextView tvNoiDung;
	Button btnDapAn1;
	TextView tvDapAn1;
	Button btnDapAn2;
	TextView tvDapAn2;
	Button btnDapAn3;
	TextView tvDapAn3;
	Button btnDapAn4;
	TextView tvDapAn4;
	TextView tvSoCauHoanThanh;
	Button btnPrevious;
	Button btnNext;

	int tongSoCauHoi = 0;
	int soCauHoanThanh = 0;
	int flag = 0;

	CountDownTimer countDown;
	long totalTimeCountInMilliseconds;

	public Dialog dialog;
	
	String ipGV = "";
	String portGV = "";
	String ipHS = "";
	String mshs = "";
	String tenHS = "";			
	String hoanthanh = "";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.screen_lam_bai);
		
		SharedPreferences prefs = getSharedPreferences("TaiKhoanGV", 0);
		ipGV = prefs.getString("ip", "").toString();
		portGV = prefs.getString("port", "").toString();
		
		prefs = getSharedPreferences("TaiKhoanHS", 0);
		tenHS = prefs.getString("hoten", "").toString();
		mshs = prefs.getString("mshs", "").toString();
		ipHS = prefs.getString("ip", "").toString();

		try {
			init();
		} catch (IOException e) {
			e.printStackTrace();
		}

		imgClock = (ImageView) findViewById(R.id.imgAlarmClock);
		imgClock.postDelayed(onEverySecond, 0);

		/**************** dialog ******************/
		dialog = new Dialog(this);

		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.dialog_tinh_gio_lam_bai);
		dialog.setCancelable(false);

		TextView tvTitle = (TextView) dialog.findViewById(R.id.tvTitle);
		tvTitle.setText("Kiểm tra 15 phút");

		ProgressBar prWait = (ProgressBar) dialog.findViewById(R.id.prWait);

		dialog.show();
		/**************** end dialog ******************/

		tvTimer = (TextView) findViewById(R.id.tvTimer);

		totalTimeCountInMilliseconds = 61 * 1000;

		tongSoCauHoi = cauhoi1.length;

		tvSoThuTuCauHoi = (TextView) findViewById(R.id.tvCauHoi);
		tvSoThuTuCauHoi.setText(cauhoi1[0]);

		tvNoiDung = (TextView) findViewById(R.id.tvNoiDung);
		tvNoiDung.setText(Html.fromHtml(listCauHoi15.get(0).getCauhoi().trim()));

		tvDapAn1 = (TextView) findViewById(R.id.tvDapAn1);
		tvDapAn1.setText(Html.fromHtml(listCauHoi15.get(0).getLuaChon1().trim()));
		tvDapAn2 = (TextView) findViewById(R.id.tvDapAn2);
		tvDapAn2.setText(Html.fromHtml(listCauHoi15.get(0).getLuaChon2().trim()));
		tvDapAn3 = (TextView) findViewById(R.id.tvDapAn3);
		tvDapAn3.setText(Html.fromHtml(listCauHoi15.get(0).getLuaChon3().trim()));
		tvDapAn4 = (TextView) findViewById(R.id.tvDapAn4);
		tvDapAn4.setText(Html.fromHtml(listCauHoi15.get(0).getLuaChon4().trim()));

		btnDapAn1 = (Button) findViewById(R.id.btnDapAn1);
		btnDapAn1.setOnClickListener(chooseAnswer);
		btnDapAn2 = (Button) findViewById(R.id.btnDapAn2);
		btnDapAn2.setOnClickListener(chooseAnswer);
		btnDapAn3 = (Button) findViewById(R.id.btnDapAn3);
		btnDapAn3.setOnClickListener(chooseAnswer);
		btnDapAn4 = (Button) findViewById(R.id.btnDapAn4);
		btnDapAn4.setOnClickListener(chooseAnswer);

		tvSoCauHoanThanh = (TextView) findViewById(R.id.tvResult);
		tvSoCauHoanThanh.setText(soCauHoanThanh + "/" + tongSoCauHoi);

		btnPrevious = (Button) findViewById(R.id.btnPrevious);
		btnPrevious.setVisibility(View.INVISIBLE);
		btnPrevious.setOnClickListener(previous);

		btnNext = (Button) findViewById(R.id.btnNext);
		btnNext.setOnClickListener(next);

	}

	public void startTest() {
		countDown = new CountDownTimer(totalTimeCountInMilliseconds, 500) {

			@Override
			public void onTick(long millisUntilFinished) {
				long seconds = millisUntilFinished / 1000;
				tvTimer.setText(String.format("%02d", seconds / 60) + ":"
						+ String.format("%02d", seconds % 60));
			}

			@Override
			public void onFinish() {
				SharedPreferences prefs = getSharedPreferences("LAMBAI", 0);
				SharedPreferences.Editor editor = prefs.edit();
				editor.putInt("start", 0);
				editor.commit();
				Intent intent = new Intent(LamBaiKT15.this, GuiBaiKiemTra.class);

				Bundle b = new Bundle();
				String dapanHS = "";
				for (int i = 0; i < dapan.length; i++) {
					dapanHS += dapan[i];
				}
				b.putString("dapanHS", dapanHS.toString().trim());
				b.putString("kiemtra", "BKT15");
				intent.putExtras(b);
				startActivity(intent);
				finish();
			}
		}.start();
	}

	public Runnable onEverySecond = new Runnable() {
		public void run() {
			new WaitAsyncTask(getApplicationContext()).execute();
		}
	};

	final class WaitAsyncTask extends AsyncTask<Void, Void, Void> {

		private Context context;
		private int start = 0;

		public WaitAsyncTask(Context _ctx) {
			this.context = _ctx;
		}

		@Override
		protected Void doInBackground(Void... param) {
			SharedPreferences prefs = context.getSharedPreferences("LAMBAI", 0);
			start = prefs.getInt("start", 0);
			return null;
		}

		@Override
		protected void onPostExecute(final Void unused) {
			if (start == 1) {
				imgClock.removeCallbacks(onEverySecond);
				dialog.dismiss();
				startTest();
			} else {
				imgClock.postDelayed(onEverySecond, 0);
			}
		}

	}

	private void init() throws IOException {
		SharedPreferences prefs = getSharedPreferences("FILENHAN", 0);
		title = prefs.getString("kind", "");
		nameFile = prefs.getString("name", "");
		path += nameFile;
		readXLSfile(path);
	}

	private void readXLSfile(String path) throws IOException {
		File inputWorkbook = new File(path);
		Workbook w;

		try {
			w = Workbook.getWorkbook(inputWorkbook);
			Sheet sheet = w.getSheet(0);

			int stt = 1;
			int count = 0;
			for (int j = 0; j < sheet.getColumns(); j++) {
				Log.d("size", "" + sheet.getRows());
				for (int i = 0; i < sheet.getRows(); i++) {
					Cell cell = sheet.getCell(j, i);
					if (count == 0) {
						cauhoi.setCauhoi(chuanHoa(cell.getContents()));
						count++;
					} else if (count == 1) {
						cauhoi.setLuaChon1(chuanHoa(cell.getContents()));
						count++;
					} else if (count == 2) {
						cauhoi.setLuaChon2(chuanHoa(cell.getContents()));
						count++;
					} else if (count == 3) {
						cauhoi.setLuaChon3(chuanHoa(cell.getContents()));
						count++;
					} else if (count == 4) {
						cauhoi.setLuaChon4(chuanHoa(cell.getContents()));
						count++;
					} else if (count == 5) {
						cauhoi.setStt(stt);
						cauhoi.setDapAn(0);
						listCauHoi15.add(cauhoi);
						cauhoi = new CauHoi15();
						stt++;
						count = 0;
					}
				}
			}

		} catch (BiffException e) {
			e.printStackTrace();
		}
	}

	private String chuanHoa(String str) {
		str = " " + str + " ";

		int i = 0;
		int len = str.length();
		String tmp = "";
		// " 2Na+ + SO42- -> Na2SO4 "
		while (i < len) {

			if ('1' <= str.charAt(i) && str.charAt(i) <= '9'
					&& (str.charAt(i + 1) == '+' || str.charAt(i + 1) == '-')) {

				tmp = str.substring(0, i) + "<sup><small>"
						+ str.substring(i, i + 2) + "</small></sup>"
						+ str.substring(i + 2, len);

				len = tmp.length();
				str = tmp;
				i += 27;
				tmp = "";
			} else if ('1' <= str.charAt(i)
					&& str.charAt(i) <= '9'
					&& (str.codePointAt(i - 1) == 41 || str.codePointAt(i - 1) > 57)
					&& str.charAt(i + 1) != '+' && str.charAt(i + 1) != '-') {
				
				tmp = str.substring(0, i) + "<sub><small>" + str.charAt(i)
						+ "</small></sub>" + str.substring(i + 1, len);
				
				len = tmp.length();
				str = tmp;
				i += 27;
				tmp = "";
			} else if ((str.charAt(i) == '+' || str.codePointAt(i) == '-')
					&& str.codePointAt(i - 1) != 32
					&& str.codePointAt(i + 1) == 32) {
				
				tmp = str.substring(0, i) + "<sub><small>" + str.charAt(i)
						+ "</small></sub>" + str.substring(i + 1, len);
				
				len = tmp.length();
				str = tmp;
				i += 27;
				tmp = "";
			} else {
				i++;
			}

		};

		return str.trim();

	}

	OnClickListener chooseAnswer = new OnClickListener() {

		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.btnDapAn1:
				dapan[flag] = "A";
				changeBackGround("A");
				break;
			case R.id.btnDapAn2:
				dapan[flag] = "B";
				changeBackGround("B");
				break;
			case R.id.btnDapAn3:
				dapan[flag] = "C";
				changeBackGround("C");
				break;
			case R.id.btnDapAn4:
				dapan[flag] = "D";
				changeBackGround("D");
				break;
			}

			soCauHoanThanh = 0;
			for (int i = 0; i < dapan.length; i++) {
				if (dapan[i] != "F") {
					soCauHoanThanh += 1;
				}
			}
			tvSoCauHoanThanh.setText(soCauHoanThanh + "/" + tongSoCauHoi);
			
			hoanthanh = "" + (soCauHoanThanh * 100 / 15);
			new SendPercentAsyncTask(tenHS, mshs, ipHS, hoanthanh).execute();
		}
	};

	final class SendPercentAsyncTask extends AsyncTask<Void, Void, Void> {
		
		String tenHS = "";
		String mshs = "";
		String ipHS = "";
		String hoanthanh = "";
		
		public SendPercentAsyncTask(String _tenHS, String _mshs, String _ipHS, String _hoanThanh) {
			this.tenHS = _tenHS;
			this.mshs = _mshs;
			this.ipHS = _ipHS;
			this.hoanthanh = _hoanThanh;
		}

		@Override
		protected Void doInBackground(Void... params) {
			try {
				TCPClient client = new TCPClient(getApplicationContext(), ipGV, Integer.parseInt(portGV));
				client.guiCapNhatKT15(tenHS, mshs, ipHS, hoanthanh);
			} catch (NumberFormatException e) {
				e.printStackTrace();
			} catch (UnknownHostException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}
		
	}
	
	OnClickListener previous = new OnClickListener() {

		public void onClick(View v) {
			flag -= 1;
			tvSoThuTuCauHoi.setText(cauhoi1[flag]);
			
			tvNoiDung.setText(Html.fromHtml(listCauHoi15.get(flag).getCauhoi().trim()));
			tvDapAn1.setText(Html.fromHtml(listCauHoi15.get(flag).getLuaChon1().trim()));
			tvDapAn2.setText(Html.fromHtml(listCauHoi15.get(flag).getLuaChon2().trim()));
			tvDapAn3.setText(Html.fromHtml(listCauHoi15.get(flag).getLuaChon3().trim()));
			tvDapAn4.setText(Html.fromHtml(listCauHoi15.get(flag).getLuaChon4().trim()));
			
			changeBackGround(dapan[flag]);
			_PreviousNext(flag);
		}

	};

	OnClickListener next = new OnClickListener() {

		public void onClick(View v) {
			flag += 1;
			tvSoThuTuCauHoi.setText(cauhoi1[flag]);
			
			tvNoiDung.setText(Html.fromHtml(listCauHoi15.get(flag).getCauhoi().trim()));
			tvDapAn1.setText(Html.fromHtml(listCauHoi15.get(flag).getLuaChon1().trim()));
			tvDapAn2.setText(Html.fromHtml(listCauHoi15.get(flag).getLuaChon2().trim()));
			tvDapAn3.setText(Html.fromHtml(listCauHoi15.get(flag).getLuaChon3().trim()));
			tvDapAn4.setText(Html.fromHtml(listCauHoi15.get(flag).getLuaChon4().trim()));
			
			changeBackGround(dapan[flag]);
			_PreviousNext(flag);
		}
	};

	private void _PreviousNext(int flag) {
		if (flag == 0) {
			btnPrevious.setVisibility(View.INVISIBLE);
			btnNext.setVisibility(View.VISIBLE);
		} else if (flag == tongSoCauHoi - 1) {
			btnPrevious.setVisibility(View.VISIBLE);
			btnNext.setVisibility(View.INVISIBLE);
		} else {
			btnPrevious.setVisibility(View.VISIBLE);
			btnNext.setVisibility(View.VISIBLE);
		}
	}

	private void changeBackGround(String answer) {
		
		if (answer == "A") {
			btnDapAn1.setBackgroundResource(R.drawable.select);
			btnDapAn2.setBackgroundResource(R.drawable.unselect);
			btnDapAn3.setBackgroundResource(R.drawable.unselect);
			btnDapAn4.setBackgroundResource(R.drawable.unselect);
		} else if (answer == "B") {
			
			btnDapAn1.setBackgroundResource(R.drawable.unselect);
			btnDapAn2.setBackgroundResource(R.drawable.select);
			btnDapAn3.setBackgroundResource(R.drawable.unselect);
			btnDapAn4.setBackgroundResource(R.drawable.unselect);
		} else if (answer == "C") {
			btnDapAn1.setBackgroundResource(R.drawable.unselect);
			btnDapAn2.setBackgroundResource(R.drawable.unselect);
			btnDapAn3.setBackgroundResource(R.drawable.select);
			btnDapAn4.setBackgroundResource(R.drawable.unselect);
		} else if (answer == "D") {
			btnDapAn1.setBackgroundResource(R.drawable.unselect);
			btnDapAn2.setBackgroundResource(R.drawable.unselect);
			btnDapAn3.setBackgroundResource(R.drawable.unselect);
			btnDapAn4.setBackgroundResource(R.drawable.select);
		} else {
			btnDapAn1.setBackgroundResource(R.drawable.unselect);
			btnDapAn2.setBackgroundResource(R.drawable.unselect);
			btnDapAn3.setBackgroundResource(R.drawable.unselect);
			btnDapAn4.setBackgroundResource(R.drawable.unselect);
		}
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			return false;
		}
		return false;
	}
}
